package com.piece.admin.controller.system;

import com.piece.admin.model.TbSysUser;
import com.piece.admin.service.TbSysUserService;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.enums.OptionType;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.support.dto.UserDetailDTO;
import com.piece.core.framework.util.collection.MapUtil;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.mongo.entity.MongoMessage;
import com.piece.core.mongo.service.MongoMessageService;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.async.AsyncManager;
import com.piece.core.web.controller.FrameWorkController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.*;

@RestController
@Api(tags = {"系统消息管理"})
@RequestMapping("/api/message")
public class SysMessageController extends FrameWorkController {

    @Resource
    private MongoMessageService mongoMessageService;

    @Resource
    private TbSysUserService tbSysUserService;

    @PostMapping("/table")
    @AclPermission(code = "tool:notice:view")
    @ApiOperation(value = "查询系统消息分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table(UserDetailDTO userDetail) {
        QueryTable queryTable = initTable();
        String is_mine = getRequest().getParameter("mine");

        if (StatusType.NORMAL.getCode().equals(is_mine)) {
            Map param = queryTable.getParams();
            param.put("Q_receiver_S_EQ", userDetail.getId());
            param.put("Q_type_S_EQ", OptionType.MESSAGE.getCode());
            param.put("Q_status_S_EQ", StatusType.NORMAL.getCode());
        }

        DataTable dataTable = mongoMessageService.findPage(queryTable);
        List<MongoMessage> messages = dataTable.getData();

        TbSysUser receiver;
        for (MongoMessage message : messages) {
            if (message.getReceiver() != null && !"all".equals(message.getReceiver())) {
                receiver = tbSysUserService.findById(Convert.toLong(message.getReceiver()));
                if (null != receiver) {
                    message.setReceiver(receiver.getLoginName());
                }
            }
        }
        dataTable.setData(messages);
        return success(dataTable);
    }

    @GetMapping("/load")
    @ApiOperation(value = "加载系统消息详情")
    @ApiImplicitParam(name = "id", value = "消息主键")
    public AjaxResponse load() {
        String id = getRequest().getParameter("id");
        MongoMessage message = new MongoMessage();
        if (StringUtil.isNotEmpty(id)) {
            message = mongoMessageService.findById(id);
        }

        return success(message);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "tool:notice:add,tool:notice:edit")
    @ApiOperation(value = "保存系统消息")
    @ApiImplicitParam(name = "消息数据", dataTypeClass = MongoMessage.class, type = "body")
    public AjaxResponse save() {
        MongoMessage message = new MongoMessage();
        try {
            initDB(message);

            List<TbSysUser> users = new ArrayList<>();
            if (StringUtil.isNotEmpty(message.getReceiver())) {
                users.addAll(tbSysUserService.findList(MapUtil.builder(new HashMap<String, Object>())
                                .put("status", StatusType.NORMAL.getCode())
                                .put("Q_userId_L_IN", Arrays.asList(Convert.toLongArray(message.getReceiver())))
                                .build()));
            }
            if (StringUtil.isNotEmpty(message.getReceiverRole())) {
                users.addAll(tbSysUserService.findUserByRoles(Arrays.asList(Convert.toLongArray(message.getReceiverRole()))));
            }
            // 删除历史通知
            if (StringUtil.isNotEmpty(message.getId())) {
                mongoMessageService.delete(message.getId());
            }

            if (users.size() > 0) {
                for (TbSysUser user : users) {
                    AsyncManager.getInstance().submit(new TimerTask() {
                        @Override
                        public void run() {
                            if (null != user.getUserId() && user.getUserId() != 0L) {
                                message.setReceiver(Convert.toStr(user.getUserId()));
                            }
                            mongoMessageService.insert(message);
                        }
                    });
                }
            } else {
                message.setReceiver("all");
                mongoMessageService.insert(message);
            }

            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "tool:notice:delete")
    @ApiOperation(value = "删除系统消息")
    @ApiImplicitParam(name = "ids", value = "消息ID")
    public AjaxResponse deleteMessage() {
        String ids = getRequest().getParameter("ids");
        if (null != ids) {
            String[] idArr = ids.split(FrameWorkConstants.SPLIT_PARAM);
            for (String id : idArr) {
                mongoMessageService.delete(id);
            }
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @PostMapping("/read/{id}")
    @ApiOperation(value = "已读系统消息")
    @ApiImplicitParam(name = "id", value = "消息主键", type = "path")
    public AjaxResponse read(@PathVariable String id) {
        MongoMessage message = mongoMessageService.findById(id);
        if (null != message) {
            // 消息设置为已读
            message.setStatus(StatusType.READ.getCode());
            mongoMessageService.update(message);
        }

        return success();
    }

    @PostMapping("/count")
    @ApiOperation(value = "查询系统消息数量")
    public AjaxResponse count(UserDetailDTO userDetail) {
        return success(mongoMessageService.countMessageByUser(userDetail));
    }
}
